package api

import (
	"strconv"
	"time"

	"gitee.com/war2001/NiuMaEasyGo/model"
	"gitee.com/war2001/NiuMaEasyGo/nm_core/middleware"
	"gitee.com/war2001/NiuMaEasyGo/nm_core/router"
	"github.com/gin-gonic/gin"
)

// LoginLogController 登录日志控制器
type LoginLogController struct {
	loginLogService model.LoginLogService
}

// NewLoginLogController 创建登录日志控制器
func NewLoginLogController(loginLogService model.LoginLogService) *LoginLogController {
	return &LoginLogController{
		loginLogService: loginLogService,
	}
}

// RegisterRoutes 注册路由 (旧方式，保留用于兼容)
func (c *LoginLogController) RegisterRoutes(r *gin.RouterGroup) {
	loginLog := r.Group("/login-log")
	{
		// 需要认证的接口
		authLoginLog := loginLog.Group("")
		authLoginLog.Use(middleware.JWTAuth())
		{
			authLoginLog.GET("/list", c.List)
			authLoginLog.GET("/my", c.MyLoginLogs)
			authLoginLog.GET("/abnormal", c.AbnormalLoginLogs)
			authLoginLog.GET("/recent", c.RecentLoginLogs)
			authLoginLog.POST("/clear", c.ClearLoginLogs)
		}
	}
}

// ListMetadata 登录日志列表元数据
func (c *LoginLogController) ListMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "登录日志",
		Path:         "/system/login-log",
		Component:    "/system/login-log/index",
		Icon:         "log",
		Permission:   "system:login-log:list",
		ParentPath:   "/system",
		MenuType:     "menu",
		MenuCategory: "system",
		Method:       "GET",
		APIPath:      "/login-log/list",
		RequireAuth:  true,
		OrderNum:     6,
	}
}

// MyLoginLogsMetadata 我的登录日志元数据
func (c *LoginLogController) MyLoginLogsMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "我的登录日志",
		Path:         "/user/login-log",
		Component:    "/user/login-log/index",
		Icon:         "history",
		Permission:   "",
		ParentPath:   "/user",
		MenuType:     "menu",
		MenuCategory: "common",
		Method:       "GET",
		APIPath:      "/login-log/my",
		RequireAuth:  true,
		OrderNum:     2,
	}
}

// AbnormalLoginLogsMetadata 异常登录日志元数据
func (c *LoginLogController) AbnormalLoginLogsMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "异常登录",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:login-log:abnormal",
		ParentPath:   "/system/login-log",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "GET",
		APIPath:      "/login-log/abnormal",
		RequireAuth:  true,
		OrderNum:     1,
	}
}

// RecentLoginLogsMetadata 最近登录日志元数据
func (c *LoginLogController) RecentLoginLogsMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "最近登录",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "",
		ParentPath:   "",
		MenuType:     "button",
		MenuCategory: "common",
		Method:       "GET",
		APIPath:      "/login-log/recent",
		RequireAuth:  true,
		Hidden:       true,
		OrderNum:     1,
	}
}

// ClearLoginLogsMetadata 清理登录日志元数据
func (c *LoginLogController) ClearLoginLogsMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "清理日志",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "system:login-log:clear",
		ParentPath:   "/system/login-log",
		MenuType:     "button",
		MenuCategory: "system",
		Method:       "POST",
		APIPath:      "/login-log/clear",
		RequireAuth:  true,
		OrderNum:     2,
	}
}

// List 获取登录日志列表
func (c *LoginLogController) List(ctx *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	// 构建查询条件
	query := make(map[string]interface{})
	if username := ctx.Query("username"); username != "" {
		query["username"] = username
	}
	if loginIP := ctx.Query("login_ip"); loginIP != "" {
		query["login_ip"] = loginIP
	}
	if location := ctx.Query("login_location"); location != "" {
		query["login_location"] = location
	}
	if status := ctx.Query("status"); status != "" {
		statusInt, _ := strconv.Atoi(status)
		query["status"] = statusInt
	}
	if isAbnormal := ctx.Query("is_abnormal"); isAbnormal != "" {
		abnormalInt, _ := strconv.Atoi(isAbnormal)
		query["is_abnormal"] = abnormalInt
	}
	if startTime := ctx.Query("start_time"); startTime != "" {
		startTimeObj, err := time.Parse("2006-01-02 15:04:05", startTime)
		if err == nil {
			query["start_time"] = startTimeObj
		}
	}
	if endTime := ctx.Query("end_time"); endTime != "" {
		endTimeObj, err := time.Parse("2006-01-02 15:04:05", endTime)
		if err == nil {
			query["end_time"] = endTimeObj
		}
	}

	// 查询登录日志
	logs, total, err := c.loginLogService.List(page, pageSize, query)
	if err != nil {
		middleware.ResponseError(ctx, 500, "获取登录日志失败: "+err.Error())
		return
	}

	// 返回结果
	middleware.ResponseSuccess(ctx, gin.H{
		"list":  logs,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// MyLoginLogs 获取当前用户的登录日志
func (c *LoginLogController) MyLoginLogs(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		middleware.ResponseError(ctx, 401, "未获取到用户信息")
		return
	}

	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	// 查询用户登录日志
	logs, total, err := c.loginLogService.GetUserLoginLogs(userID.(uint), page, pageSize)
	if err != nil {
		middleware.ResponseError(ctx, 500, "获取登录日志失败: "+err.Error())
		return
	}

	// 返回结果
	middleware.ResponseSuccess(ctx, gin.H{
		"list":  logs,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// AbnormalLoginLogs 获取异常登录日志
func (c *LoginLogController) AbnormalLoginLogs(ctx *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	// 查询异常登录日志
	logs, total, err := c.loginLogService.GetAbnormalLoginLogs(page, pageSize)
	if err != nil {
		middleware.ResponseError(ctx, 500, "获取异常登录日志失败: "+err.Error())
		return
	}

	// 返回结果
	middleware.ResponseSuccess(ctx, gin.H{
		"list":  logs,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// RecentLoginLogs 获取最近登录日志
func (c *LoginLogController) RecentLoginLogs(ctx *gin.Context) {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		middleware.ResponseError(ctx, 401, "未获取到用户信息")
		return
	}

	// 获取限制参数
	limit, _ := strconv.Atoi(ctx.DefaultQuery("limit", "5"))
	if limit > 20 {
		limit = 20
	}

	// 查询最近登录日志
	logs, err := c.loginLogService.GetRecentLoginLogs(userID.(uint), limit)
	if err != nil {
		middleware.ResponseError(ctx, 500, "获取最近登录日志失败: "+err.Error())
		return
	}

	// 返回结果
	middleware.ResponseSuccess(ctx, logs)
}

// ClearLoginLogs 清理登录日志
func (c *LoginLogController) ClearLoginLogs(ctx *gin.Context) {
	// 获取天数参数
	days, _ := strconv.Atoi(ctx.DefaultQuery("days", "30"))
	if days <= 0 {
		middleware.ResponseError(ctx, 400, "清理天数必须大于0")
		return
	}

	// 清理登录日志
	err := c.loginLogService.ClearLoginLogs(days)
	if err != nil {
		middleware.ResponseError(ctx, 500, "清理登录日志失败: "+err.Error())
		return
	}

	// 返回结果
	middleware.ResponseSuccess(ctx, "清理登录日志成功")
}
